package com.serge.smartdacha.model;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsParser {

    public SmsParser() {
    }

    public <T extends Controller> T extract(String sms, Class<T> controllerClass) {
        Map<String, Controller> parse = parse(sms);
        for (Controller controller : parse.values()) {
            if(controller.getClass().equals(controllerClass)) {
                return (T)controller;
            }
        }
        return null;
    }

    public Map<String, Controller> parse(String sms) {

        SortedMap<String, Controller> controllers = new TreeMap<String, Controller>();

        Pattern controllerPattern = Pattern.compile("([\\w\\d]+)\\(([\\d\\w,=-]+)\\)");
        Pattern valuesPattern = Pattern.compile("([\\w]+)=(-?[\\d]+)");

        Matcher matcher = controllerPattern.matcher(sms);
        while (matcher.find()) {
            String id = matcher.group(1);
            String values = matcher.group(2);

            Map<String, String> map = new HashMap<String, String>();
            Matcher valuesMatcher = valuesPattern.matcher(values);
            while (valuesMatcher.find()) {
                String name = valuesMatcher.group(1);
                String value = valuesMatcher.group(2);
                map.put(name, value);
            }

            Controller controller = null;
            if (id.equalsIgnoreCase("C1")) {
                controller = new TRController(id);
            } else if (id.equalsIgnoreCase("C2")) {
                controller = new TRController(id);
            } else if (id.equalsIgnoreCase("L")) {
                controller = new CosmController();
            } else if (id.equalsIgnoreCase("P")) {
                controller = new PerimeterController();
            } else if (id.equalsIgnoreCase("FM")) {
                controller = new FMController();
            }
            if(controller != null) {
                controller.init(map);
                controllers.put(id, controller);
            }
        }

        return controllers;
    }

}
